//
//  AliMNSClient.m
//  AlibabaCloudMNSiOS
//
//  Created by David Chen on 28/03/2017.
//  Copyright © 2017 AliCloud. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "AliMNSClient.h"
#import "AliMNSHttp.h"

@implementation AliMNSClient
@synthesize host;
@synthesize accessId;
@synthesize accessKey;
@synthesize version;
@synthesize securityToken;
@synthesize http;

-(instancetype)initWithHost:(NSString*) _host
     withAccessId:(NSString*) _accessId
    withAccessKey:(NSString*) _accessKey
      withVersion:(NSString*) _version
          withSecurityToken:(NSString*) _securityToken
{
    host = _host;
    accessId = _accessId;
    accessKey = _accessKey;
    version = _version;
    securityToken = _securityToken;
    http = [AliMNSHttp new];
    http.host = host;
    return self;
}

-(void)sendRequest:(AliMNSRequestBase*)
req withResponse:(AliMNSResponseBase*)res
{
    AliMNSHttpRequestInternal* internalReq = [req buildInternalHttpRequest:self];
    AliMNSHttpResponseInternal* internalRes = [AliMNSHttpResponseInternal new];

    // send http request to Message Service.
    [http sendSyncRequest:internalReq withResponse:internalRes];

    if (internalRes.error == nil) // no network errors.
    {
        [res parseFromInternalHttpResponse: internalRes];
    }
    else
    {
        res.internalError = internalRes.error;
    }

    // throw properly exception if error occurs.
    [res checkError:internalRes];
}

-(void)sendAyncRequest:(AliMNSRequestBase*) req
          withResponse:(AliMNSResponseBase*) res
   withResponseHanlder:(void (^)(AliMNSResponseBase * ayncRes)) responseHandler
{
    AliMNSHttpRequestInternal* internalReq = [req buildInternalHttpRequest:self];
    AliMNSHttpResponseInternal* internalRes = [AliMNSHttpResponseInternal new];

    // send http request to Message Service.
    [http sendAsyncRequest:internalReq withResponse:internalRes
        withHandler: ^(AliMNSHttpResponseInternal* inRes){

        [res parseFromInternalHttpResponse: inRes];

        responseHandler(res);
    }
    ];
}


@end
